import json
import re
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.

from django.shortcuts import render
from qiniu import Auth,put_data,put_file
from iHome.utils.view import login_required
from .models import User
from django.utils.decorators import method_decorator
import json
import re

from django import http
from django.contrib.auth import authenticate, login, logout

# from django.contrib.auth.models import User

from django.http import JsonResponse
from django.views.generic.base import View
from django_redis import get_redis_connection
# Create your views here.
class ImagePutView(View):

    def post(self,request):
        user = request.user
        print(user,1)
        image_file = request.FILES.get('avatar')
    #需要填写你的 Access Key 和 Secret Key
        access_key = '34ESq7LhLzoc0Q_pxAX5d2GLbGJZ4B1J7Pf6ercu'
        secret_key = 'vHq5LC1kpuQbRfC8Lv4IX4BfjXJKxo0MOVd8xiZ9'
        #构建鉴权对象
        q = Auth(access_key, secret_key)
        #要上传的空间
        bucket_name = 'ihomeimge1'
        #上传后保存的文件名
        key = 'image_%s'%user.id
        #生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name, key, 3600)
        print(token,3)
        #要上传文件的本地路径

        ret, info = put_data(token, key,image_file )
        print(info)
        return JsonResponse({
            "data": {
                "avatar_url": "http://qes0fbg23.bkt.clouddn.com/image_%s"%user.id
            },
            "errno": "0",
            "errmsg": "头像上传成功"
            })

class UserInfoView(View):
    def get(self,request):
        user = request.user
        return JsonResponse({
            "errno": "0",
            "errmsg": "OK",
            "data": {
                "avatar": "http://qes0fbg23.bkt.clouddn.com/image_%s"%user.id,
                "create_time": user.date_joined,
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id
                }

            })

class RegisterView(View):

    def post(self, request):
        '''接收参数, 保存到数据库'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')
        # password2 = dict.get('password2')
        sms_code_client = dict.get('phonecode')

        # 2.校验(整体)
        if not all([mobile, password,sms_code_client]):
            return http.JsonResponse({'errno': 4103,
                                      'errmsg': '缺少必传参数'})
            # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': 4004,
                                      'errmsg': 'mobile格式有误'})

        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'errno': 4004,
                                      'errmsg': 'password格式有误'})

        # 5.password2 和 password
        # if password != password2:
        #     return http.JsonResponse({'code': 4004,
        #                               'errmsg': '两次输入不对'})
        redis_conn = get_redis_connection('verify_code')
        # 9.从redis中取值
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 10.判断该值是否存在
        if not sms_code_server:
            return http.JsonResponse({'errno': 4004,
                                      'errmsg': '短信验证码过期'})
        # 11.把redis中取得值和前端发的值对比
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'errno': 4004,
                                      'errmsg': '验证码有误'})

        # 12.保存到数据库 (username password mobile)
        try:
            #auth.models.User
            user = User.objects.create_user(username=mobile, mobile= mobile,password= password)
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': 4004,
                                      'errmsg': '保存到数据库出错'})

        login(request, user)
        # 13.拼接json返回
        # 生成响应对象
        response = JsonResponse({'errno': 0,
                                 'errmsg': '注册成功','data': {'name': user.username, 'user_id': user.id}})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)

        # 返回响应结果
        return response

class LoginLogoutView(View):
    #     登录接口
    def post(self, request):
        #         接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')

        #         校验（整体+单个）
        if not all([mobile, password]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '缺少必传参数'})
        user = User.objects.get(mobile=mobile)
        #       验证是否能够登录
        users = user.check_password(password)

        #       判断是否为空，如果为空，返回
        if users is None:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '用户名或者密码错误'})

        #       状态保持
        login(request, user)
        request.session.set_expiry(0)

        #       返回JsonResponse
        response = JsonResponse({'errno':0,'errmsg':'登陆成功'})
        response.set_cookie(
            'username',
            user.username,
            max_age=3600 * 24 * 14
        )
        return response


    def delete(self, request):
        # 实现退出登录逻辑
        # 清理session
        logout(request)
        # 创建resonse对象
        response = JsonResponse({'errno':0,'errmsg':'ok'})
        # 调用对象的delete_cookie方法,清除cookie
        response.delete_cookie('mobile')
        # 返回响应
        return response

    def get(self,request):
        user = request.user
        #         提供个人信息界面
        #         判断用户是否正常登录
        if user.is_authenticated:
            # 已登录
            return JsonResponse({"errno": "0","errmsg": "已登录",
                                 "data": {"name":user.username,'user_id':user.id}})
        #     未登录
        if not user.is_authenticated:
            return JsonResponse({"errno": "4101","errmsg":"未登录"})
















# 更新用户名

from django.views.generic.base import View


class UserNameChangeView(View):


    #@method_decorator(login_required) #判断是否登入,请在前序判断登入完成后开启此行代码
    def put(self, request):
        data = json.loads(request.body.decode())
        name = data.get('name')

        #校验用户名name
        if not name:
            return JsonResponse({
                "errno": "4104",
                "errmsg": "用户不存在"})
        if not re.match(r'^\w{5,20}$', name):
            return JsonResponse({
                "errno": "4004",
                "errmsg": "用户名格式有误"}, status=400)

        #处理数据,用户名更新
        user = request.user
        try:
            user.username = name
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({"errno": "4302",
                "errmsg": "文件读写错误"})

        return JsonResponse({
            "errno": "0",
            "errmsg": "修改成功"})


class Id_CardView(View):  #实名认证-------身份证和真实姓名校验姓名


    @method_decorator(login_required) #判断是否登入,请在前序判断登入完成后开启此行代码
    def post(self, request):

        #提取身份证和真是姓名
        data = json.loads(request.body.decode())
        real_name = data.get('real_name')
        id_card = data.get('id_card')

        #校验身份证和真实姓名
        if not all([real_name, id_card]):
            return JsonResponse({
                "errno": "4004",
                "errmsg": "缺少参数"
            })
        if not re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$', id_card):
            return JsonResponse({
                "errno": "4103",
                "errmsg": "身份证格式不正确"
            })

        #保存数据
        user = request.user
        try:
            user.id_card = id_card,
            user.real_name = real_name
            user.save()
        except Exception as e:
            print(e)

        return JsonResponse({
                "errno": "0",
                "errmsg": "认证信息保存成功"
            })




